package com.zjj.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjj.reggie.common.R;
import com.zjj.reggie.entity.Employee;
import com.zjj.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


@Slf4j // 日志
@RestController// 控制器
@RequestMapping("/employee") // 请求映射

public class EmployeeController {
    // 注入 EmployeeService
    @Autowired
    private EmployeeService employeeService;// 员工服务

    /**
     * 登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        /**
         * TODO: 登录逻辑
         */

        //1.将页面提交的密码password进行MD5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2.根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //3.判断查询结果是否为空
        if (emp == null) {
            return R.error("账号不存在");
        }

        //4.判断密码是否正确
        if (!emp.getPassword().equals(password)) {
            return R.error("密码错误");
        }
        //5.查看员工是否被禁用
        if (emp.getStatus() == 0) {
            return R.error("账号以被禁用");
        }

        //6.登录成功，将用户id存入session
        request.getSession().setAttribute("employee", emp.getId());
//        redisTemplate.opsForValue().set("employee",emp.getId());
        //7.返回员工信息
        return R.success(emp);
    }

    // 注销
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        //1.清除session中的用户id
        request.getSession().removeAttribute("employee");
        //2.返回成功信息
        return R.success("注销成功");
    }

    /**
     * 新增员工
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> register(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("新增员工：{}", employee);
        //1.设置默认密码123456，加密后存入数据库
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //2.设置创建时间
//        employee.setCreateTime(LocalDateTime.now());
//        //3.设置更新时间
//        employee.setUpdateTime(LocalDateTime.now());
//        //4.获得当前登录用户id
//        Long empId = (Long) request.getSession().getAttribute("employee");
//        //5.设置创建人和更新人
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);
        //6.保存员工信息

        employeeService.save(employee);
        //7.返回成功信息
        return R.success("新增员工成功");
    }

    /**
     * 分页查询员工
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("分页查询员工：page={},pageSize={},name={}",page,pageSize,name);

        //1.构造分页构造器
        Page pageInfo = new Page(page,pageSize);
        //2.构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //添加一个过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);//模糊查询
        //添加一个排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //3.执行查询
        employeeService.page(pageInfo,queryWrapper);
        //4.返回分页信息
        return R.success(pageInfo);
    }

    /**
     * 根据id修改员工信息
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee){
        log.info("更新员工：{}", employee.toString());
        //获得当前登录用户id
//        Long empId = (Long)request.getSession().getAttribute("employee");
//        //1.设置更新时间
//        employee.setUpdateTime(LocalDateTime.now());
//        //2.设置更新人
//        employee.setUpdateUser(empId);
        //3.更新员工信息


        long  id = Thread.currentThread().getId();
        log.info("线程id：{}",id);

        employeeService.updateById(employee);

        return R.success("更新成功");
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(HttpServletRequest request, @PathVariable("id") Long id){//id路径参数(变量)
        log.info("查询员工：id={}", id);
        //1.查询员工信息
        Employee employee = employeeService.getById(id);
        if (employee == null) {
            return R.error("员工不存在");
        }
        //2.返回员工信息
        return R.success(employee);
    }
}
